<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="home-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-inner">
        <h1 class="search-title">查找您理想的民宿</h1>
        
        <div class="search-box">
          <el-row :gutter="0">
            <el-col :span="17">
              <el-input 
                v-model="searchForm.keyword" 
                placeholder="目的地/民宿名称" 
                class="search-input"
              />
            </el-col>
            <el-col :span="7">
              <el-button type="primary" class="search-button" @click="navigateToSearch">
                搜索
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-select v-model="filters.area" placeholder="地区" clearable style="width: 100%">
            <el-option
              v-for="item in areaOptions"
              :key="item.name"
              :label="item.label"
              :value="item.name"
            />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select v-model="filters.type" placeholder="民宿类型" clearable style="width: 100%">
            <el-option
              v-for="item in typeOptions"
              :key="item.name"
              :label="item.label"
              :value="item.name"
            />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select v-model="filters.price" placeholder="价格区间" clearable style="width: 100%">
            <el-option
              v-for="item in priceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-select v-model="filters.capacity" placeholder="容纳人数" clearable style="width: 100%">
            <el-option
              v-for="item in capacityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" plain @click="applyFilters">应用筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-col>
      </el-row>
    </div>
    
    <!-- 民宿列表 -->
    <div class="homestay-list">
      <el-row :gutter="20">
        <el-col
          v-for="homestay in displayedHomestays"
          :key="homestay.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="homestay-card" shadow="hover" @click="navigateToDetail(homestay.id)">
            <div class="homestay-image">
              <img :src="homestay.img" :alt="homestay.name" />
              <span class="homestay-price">¥{{ homestay.price }}/晚</span>
            </div>
            <div class="homestay-info">
              <h3 class="homestay-name">{{ homestay.name }}</h3>
              <p class="homestay-area">
                <el-icon><Location /></el-icon> {{ homestay.area }}
              </p>
              <p class="homestay-type">{{ homestay.type }}</p>
              <div class="homestay-rating">
                <el-rate
                  v-model="homestay.rating"
                  disabled
                  text-color="#ff9900"
                  score-template="{value}"
                />
                <span>浏览 {{ homestay.viewCount }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 分页 -->
      <div class="pagination-section" v-if="homestays.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    
    <!-- 推荐区域 -->
    <div class="recommendation-section">
      <h2 class="section-title">热门推荐</h2>
      <el-row :gutter="20">
        <el-col
          v-for="homestay in recommendedHomestays"
          :key="homestay.id"
          :xs="24"
          :sm="12"
          :md="8"
        >
          <el-card class="homestay-card" shadow="hover" @click="navigateToDetail(homestay.id)">
            <div class="homestay-image">
              <img :src="homestay.img" :alt="homestay.name" />
              <span class="homestay-price">¥{{ homestay.price }}/晚</span>
            </div>
            <div class="homestay-info">
              <h3 class="homestay-name">{{ homestay.name }}</h3>
              <p class="homestay-area">
                <i class="el-icon-location"></i> {{ homestay.area }}
              </p>
              <p class="homestay-description">{{ homestay.description.substring(0, 50) }}...</p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 资讯区域 -->
    <div class="news-section">
      <h2 class="section-title">最新资讯</h2>
      <el-row :gutter="20">
        <el-col
          v-for="news in latestNews"
          :key="news.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card class="news-card" shadow="hover" @click="navigateToNews(news.id)">
            <div class="news-image">
              <img :src="news.img" :alt="news.title" />
            </div>
            <div class="news-info">
              <h3 class="news-title">{{ news.title }}</h3>
              <p class="news-summary">{{ news.summary }}</p>
              <div class="news-meta">
                <span class="news-time">
                  <i class="el-icon-time"></i>
                  {{ news.time }}
                </span>
                <span class="news-views">
                  <i class="el-icon-view"></i>
                  <el-icon><View /></el-icon> {{ news.viewCount }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <div class="view-more">
        <el-button type="primary" plain @click="navigateToNewsList">查看更多资讯</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
// 路由
const router = useRouter()
// 获取民宿数据
const homestays = ref([])
const loading = ref(false)
const typeOptions = ref([])
const areaOptions = ref([])
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

import { 
  Location, 
  View
} from '@element-plus/icons-vue'
// 搜索表单
const searchForm = ref({
  keyword: '',
  dateRange: []
})
// 筛选条件
const filters = ref({
  area: '',
  type: '',
  price: '',
  capacity: ''
})




// 价格区间选项
const priceOptions = [
  { value: '0-300', label: '¥300以下' },
  { value: '300-500', label: '¥300-500' },
  { value: '500-800', label: '¥500-800' },
  { value: '800-1000', label: '¥800-1000' },
  { value: '1000+', label: '¥1000以上' }
]

// 容纳人数选项
const capacityOptions = [
  { value: '1', label: '1人' },
  { value: '2', label: '2人' },
  { value: '4', label: '4人' },
  { value: '6', label: '6人' },
  { value: '8', label: '8人' },
  { value: '10', label: '10人' }
]

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await request.get('/homestayCategory/list')
    
    if (res.data.code === '200') {
      typeOptions.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}

//地区分类
const fetchCategoriesReing = async () => {
  try {
    const res = await request.get('/homestayRegin/list')
    
    if (res.data.code === '200') {
      areaOptions.value = res.data.data || []
    } else {
      console.error('获取分类列表失败:', res.data.msg)

    }
  } catch (error) {
    console.error('获取分类列表出错:', error)
  }
}
// 获取民宿列表
const fetchHomestays = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加筛选条件
    if (filters.value.area) {
      params.area = filters.value.area
    }
    if (filters.value.type) {
      params.type = filters.value.type
    }
    if (filters.value.price) {
      const [min, max] = filters.value.price.split('-')
      params.minPrice = min
      if (max !== '+') {
        params.maxPrice = max
      }
    }
    if (filters.value.capacity) {
      params.capacity = filters.value.capacity
    }
    
    // 发送请求获取民宿列表
    const res = await request.get('/homestays/page', { params })
    // 处理返回结果
    homestays.value = res.data.data.records || [];
    total.value = res.data.data.total || homestays.value.length
    console.log('民宿数据:', homestays.value)
  } catch (error) {
    console.error('获取民宿列表失败:', error)
    // 如果API请求失败，使用本地假数据
    fallbackToMockData()
  } finally {
    loading.value = false
  }
}
// 日期格式化工具函数
const formatDate = (timeArray) => {
  if (!timeArray || timeArray.length !== 6) return '';

  const [year, month, day, hour, minute] = timeArray;

  // 手动拼接字符串，确保格式为 "YYYY-M-D HH:MM"
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 使用本地假数据的后备方案
const fallbackToMockData = async () => {
  try {
    // 如果需要，可以在这里动态导入mock数据
    const { homestayList } = await import('../mock')
    
    // 应用筛选条件
    let filteredList = [...homestayList]
    
    if (filters.value.area) {
      filteredList = filteredList.filter(item => item.area === filters.value.area)
    }
    
    if (filters.value.type) {
      filteredList = filteredList.filter(item => item.type === filters.value.type)
    }
    
    if (filters.value.price) {
      const [min, max] = filters.value.price.split('-')
      if (max === '+') {
        filteredList = filteredList.filter(item => item.price >= parseInt(min))
      } else {
        filteredList = filteredList.filter(item => 
          item.price >= parseInt(min) && item.price <= parseInt(max)
        )
      }
    }
    
    if (filters.value.capacity) {
      filteredList = filteredList.filter(item => item.capacity == parseInt(filters.value.capacity))
    }
    
    homestays.value = filteredList
    total.value = filteredList.length
    console.log('使用模拟数据:', homestays.value)
  } catch (error) {
    console.error('加载模拟数据失败:', error)
    homestays.value = []
    total.value = 0
  }
}

// 当前页显示的民宿
const displayedHomestays = computed(() => {
  // 如果正在从API分页获取数据，则直接返回当前homestays
  return homestays.value
})

// 推荐民宿（评分最高的3个）
const recommendedHomestays = computed(() => {
  return [...homestays.value]
    .sort((a, b) => b.rating - a.rating)
    .slice(0, 3)
})

// 跳转到搜索页
const navigateToSearch = () => {
  const query = {}
  
  if (searchForm.value.keyword) {
    query.keyword = searchForm.value.keyword
  }
  
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    query.startDate = formatDate(searchForm.value.dateRange[0])
    query.endDate = formatDate(searchForm.value.dateRange[1])
  }
  
  router.push({
    path: '/search',
    query
  })
}

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1
  fetchHomestays()
}

// 重置筛选
const resetFilters = () => {
  filters.value = {
    area: '',
    type: '',
    price: '',
    capacity: ''
  }
  currentPage.value = 1
  fetchHomestays()
}

// 页码变化处理
const handlePageChange = (page) => {
  currentPage.value = page
  fetchHomestays()
  window.scrollTo(0, 0)
}
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchHomestays()
}
// 跳转到详情页
const navigateToDetail = (id) => {
  router.push(`/homestay/${id}`)
}

// 资讯相关
const latestNews = ref([])

// 获取最新资讯
const fetchLatestNews = async () => {
  try {
    const res = await request.get('/homestayNews/list', {
    })
    if (res.data.code === '200') {
      latestNews.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取最新资讯失败:', error)
  }
}

// 跳转到资讯详情页
const navigateToNews = (id) => {
  router.push(`/news/${id}`)
}

// 跳转到资讯列表页
const navigateToNewsList = () => {
  router.push('/news')
}

// 组件挂载时加载数据
onMounted(() => {
  fetchHomestays()
  fetchCategories()
  fetchLatestNews()
  fetchCategoriesReing()
})
</script>

<style scoped>
.home-container {
  padding-bottom: 2rem;
}

.search-section {
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://images.unsplash.com/photo-1566073771259-6a8506099945?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  background-position: center;
  padding: 6rem 2rem;
  margin-bottom: 2rem;
  border-radius: 0;
}

.search-inner {
  max-width: 1000px;
  margin: 0 auto;
  text-align: center;
}

.search-title {
  color: #fff;
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 2rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.search-box {
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
  background-color: white;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.search-box .el-row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.search-box .el-col {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.search-input {
  height: 45px;
  border-radius: 0;
}

.search-input :deep(.el-input__inner) {
  height: 45px;
  font-size: 16px;
  border: none;
  border-radius: 0;
  padding-left: 20px;
}

.search-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: normal;
  border-radius: 0;
  border: none;
}

.filter-section {
  margin: 2rem 0;
  padding: 1rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.homestay-list {
  margin-bottom: 3rem;
}

.homestay-card {
  margin-bottom: 20px;
  cursor: pointer;            /* 添加鼠标指针样式手型 */
  transition: transform 0.3s;  /* 添加过渡效果 */
}

.homestay-card:hover {
  transform: translateY(-5px);  /* 鼠标悬停时上移5px */
}

.homestay-image {
  position: relative; /* 设置为相对定位 */
  height: 200px;
  overflow: hidden; /* 隐藏溢出的部分 */
}

.homestay-image img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 图片覆盖整个容器,图片按比例缩放 */
  border-radius: 4px 4px 0 0; /* 添加圆角 */
}

.homestay-price {
  position: absolute; /* 设置为绝对定位 */
  bottom: 0; /* 位于底部 */
  right: 0; /* 位于右侧 */
  background-color: rgba(0, 0, 0, 0.6); /* 设置透明度 */
  color: #fff;   
  padding: 5px 10px; /* 添加内边距 */
  font-weight: bold; /* 设置粗体 */
}

.homestay-info {
  padding: 15px 10px;
}

.homestay-name {
  margin: 0 0 10px;
  font-size: 1.1rem;
  color: #333;
}

.homestay-area {
  color: #666;
  margin-bottom: 5px;
  font-size: 0.9rem;
}

.homestay-type {
  display: inline-block; /* 设置为行内块元素 */
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  font-size: 0.8rem;
  border-radius: 4px;
  margin-bottom: 8px;
}

.homestay-rating {
  display: flex; /* 设置为Flex布局 */
  align-items: center;  /* 垂直居中 */ 
  justify-content: space-between;  /* 两端对齐 */
  font-size: 0.8rem;
  color: #999;
}

.pagination-section {
  text-align: center;
  margin-top: 2rem;
}

.recommendation-section {
  margin-top: 3rem;
}

.section-title {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 5px;
  height: 20px;
  width: 5px;
  background-color: #ff6b6b;
  border-radius: 3px;
}

.homestay-description {
  color: #666;
  font-size: 0.9rem;
  margin-top: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.news-section {
  margin-top: 3rem;
}

.news-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.news-card:hover {
  transform: translateY(-5px);
}

.news-image {
  height: 180px;
  overflow: hidden;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.news-info {
  padding: 15px;
}

.news-title {
  font-size: 1.1rem;
  margin: 0 0 10px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.news-summary {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 10px;        /* 添加底部外边距 */
  display: -webkit-box;       /* 设置为Flex布局 */
  -webkit-line-clamp: 2;      /* 设置显示行数 */
  -webkit-box-orient: vertical;/* 设置垂直排列 */
  overflow: hidden;           /* 隐藏溢出的部分 */
}

.news-meta {
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  color: #999;
  font-size: 0.8rem;
}

.news-time, .news-views {
  display: flex;
  align-items: center;
  gap: 4px;
}

.view-more {
  text-align: center;
  margin-top: 2rem;
}
</style> 